package com.logic.landseaserver.ws;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.logic.landseaserver.ws.dto.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.logic.common.domain.Code;
import com.logic.common.enums.HttpCodeEnum;
import com.logic.common.exception.BusinessException;
import com.logic.common.util.CommonResult;
import com.logic.common.util.CommonResultMap;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.util.AddressUtils;
import com.logic.landseaserver.common.util.StringTools;
import com.logic.landseaserver.domain.Project;
import com.logic.landseaserver.persistence.read.ProjectReadMapper;
import com.logic.landseaserver.service.IProjectService;
import com.logic.system.service.ICodeService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONObject;

/**
 * @Author: Wells.Wei
 * @Date: 2017/4/13
 * @Description:
 */
@Path("/projects")
@Api(value="projects")
public class ProjectRest {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private IProjectService projectService;

    @Autowired
    private ICodeService codeService;
    
    @Autowired
    private ProjectReadMapper projectReadMapper;

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "创建或编辑项目（编辑项目需要在url参数中带入项目Id）", position = 1)
    public Response createProject(@ApiParam(value = "param", required = true) ProjectReqDTO projectReqDTO) {

        CommonResultMap map = new CommonResultMap();
        try {
            projectService.addOrEditProject(projectReqDTO);
            map.setData(projectReqDTO);
            map.setResult(CommonResult.SUCCESS, "Create success");
        } catch (BusinessException e) {
            logger.error("createProject error.", e);
            map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
        } catch (Exception e) {
            logger.error("createProject error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

  //根据 区域id 获取店长和城市经理
  	@POST
  	@Path("/shopAndCityKeeper/{areaCode}")
  	@Produces(MediaType.APPLICATION_JSON)
  	@Consumes(MediaType.APPLICATION_JSON)
  	@ApiOperation(value = "根据区域id获取店长，区域运营经理和管家")
    public Response shopAndCityKeeper(
        @ApiParam(value = "param", required = true) @PathParam("areaCode") String areaCode)
    {
        CommonResultMap map = new CommonResultMap();
        KeeperDTO keeper = new KeeperDTO();
        try
        {
            keeper = projectService.getKeeper(areaCode);
            map.setData(keeper);
            map.setResult(CommonResult.SUCCESS);
        }
        catch (Exception e)
        {
            logger.error("shopAndCityKeeper error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }


    @POST
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "项目列表", position = 2)
    public Response list(@ApiParam(value = "param", required = true) QueryUtil queryUtil) {
        CommonResultMap map = new CommonResultMap();
        List<ProjectDTO> projectDTOList = null;
        try {
            queryUtil.getPagingTool().calculateStartIndex();
            projectDTOList = (List<ProjectDTO>)projectService.query(queryUtil);
            Integer totalCount = queryUtil.getPagingTool().getTotalNum();
            map.setData(projectDTOList);
            map.setResultTotalCount(totalCount);
            map.setResult(CommonResult.SUCCESS);
        } catch (Exception e) {
            logger.error("list error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @GET
    @Path("/{projectId}")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "项目详情，后台", position = 4)
    public Response retrieveProjectById(
            @ApiParam(value = "param", required = true) @PathParam("projectId") Integer projectId) {
        CommonResultMap map = new CommonResultMap();
        try {
            map.setData(projectService.getProjectDetail(projectId));
        } catch (Exception e) {
            logger.error("retrieveProjectById error.", e);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @GET
    @Path("/getProjectDetailForFront/{projectId}")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "项目详情，网站和微信端", position = 4)
    public Response getProjectDetailForFront(
            @ApiParam(value = "param", required = true) @PathParam("projectId") Integer projectId) {
        CommonResultMap map = new CommonResultMap();
        try {
            ProjectDetailForFrontDTO projectDetailForFront = projectService.getProjectDetailForFront(projectId);
            map.setData(projectDetailForFront);
        } catch (Exception e) {
            logger.error("getProjectDetailForFront error.", e);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @POST
    @Path("/getProjectListForFront")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "项目列表，网站和微信端   参数格式{\"areaCode\":\"xxx\",\"isClassics\":\"xxx\"}", position = 4)
    public Response getProjectForFront(
            @ApiParam(value = "param", required = true) Map pmap) throws BusinessException {
        CommonResultMap map = new CommonResultMap();
        Map<String, Object> result = new HashMap<String, Object>();
        Integer classic =pmap.containsKey("isClassics")? Integer.parseInt((String) pmap.get("isClassics")) : null ;
        String areaCode = pmap.containsKey("areaCode")&&pmap.get("areaCode") !=""? (String) pmap.get("areaCode") : null ; //Changed by Daniel for Areacode is null
        List<Map<String,String>> projects =  projectService.getProjectListForFront(areaCode ,classic);
        
        // 是否要过滤有发布房间的项目
        String isOrder = StringTools.getString(pmap.get("isOrder"));
        // 只有为1时才过滤,专门给网站用
        if ("1".equals(isOrder))
        {
            removeNoRoomProject(projects);
        }
        
        try {
            result.put("projects", projects);
            result.put("total", projects.size());
            map.setData(result);
        } catch (Exception e) {
            logger.error("getProjectForFront error.", e);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @POST
    @Path("/getProjectListForBackend")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "项目列表，后台预约使用   参数格式{\"areaCode\":\"xxx\",\"isClassics\":\"xxx\"}", position = 4)
    public Response getProjectListForBackend(
            @ApiParam(value = "param", required = true) Map pmap) throws BusinessException {
        CommonResultMap map = new CommonResultMap();
        Map<String, Object> result = new HashMap<String, Object>();
        Integer classic =pmap.containsKey("isClassics")? Integer.parseInt((String) pmap.get("isClassics")) : null ;
        List<Map<String,String>> projects =  projectService.getProjectListForBackend((String)pmap.get("areaCode") ,classic);
        try {
            result.put("projects", projects);
            result.put("total", projects.size());
            map.setData(result);
        } catch (Exception e) {
            logger.error("getProjectListForBackend error.", e);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @PUT
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "更新项目", position = 1)
    public Response updateProject(@ApiParam(value = "param", required = true) Project project) {
        CommonResultMap map = new CommonResultMap();
        try {
            projectService.update(project);
            map.setResult(CommonResult.SUCCESS, "Create success");
        } catch (BusinessException e) {
            logger.error("updateProject error.", e);
            map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
        } catch (Exception e) {
            logger.error("updateProject error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @DELETE
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "删除项目", position = 12)
    public Response logicDelete(@ApiParam(value = "param", required = true) @QueryParam("projectIds") String ids) {
        CommonResultMap map = new CommonResultMap();
        try {
            projectService.delete(ids);
            map.setResult(CommonResult.SUCCESS);
        } catch (Exception e) {
            logger.error("logicDelete error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @GET
    @Path("/getProjectInfoWithArea")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "获取各个区域的项目信息", position = 4)
    public Response projectInfoWithArea() {
        CommonResultMap map = new CommonResultMap();
        try {
            List<Map<String, String>> projectInfoWithArea = projectService.getProjectInfoWithArea();
            map.setData(projectInfoWithArea);
        } catch (Exception e) {
            logger.error("projectInfoWithArea error.", e);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @GET
    @Path("/getAddressInfoByIp/{ip}")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Get address by request ip.", position = 4)
    public Response getAddressInfoByIp(@ApiParam(value = "param", required = true) @PathParam("ip") String ip) {
        ObjectMapper objectMapper = new ObjectMapper();
        CommonResultMap map = new CommonResultMap();
        try {
            String addressInfo = AddressUtils.getAddressByIP(ip);
            JSONObject json = new JSONObject();
            String address = (String)json.fromObject(addressInfo).get("address");
            String s = StringUtils.split(address,"|")[2];
            List<Code> area = codeService.getChildCodes("AREA");
            Map city = new HashMap<String, String>();
            for(Code c : area){
                if(c.getCodeDescZh().equals(s) ){
                    city.put("code", c.getCode());
                    city.put("city", c.getCodeDescZh());
                }
            }

            map.setData(city);
            map.setResult(CommonResult.SUCCESS, "Get success");
        } catch (Exception e) {
            logger.error("getAddressInfoByIp error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @GET
    @Path("/baseInfo/{contractId}")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "项目费用类型及价格详情，后台")
    public Response retrieveByContractId(
            @ApiParam(value = "param", required = true) @PathParam("contractId") Integer contractId) {
        CommonResultMap map = new CommonResultMap();
        try {
            map.setData(projectService.getBaseInfo(contractId));
        } catch (Exception e) {
            logger.error("retrieveByContractId error.", e);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }


    @POST
    @Path("/getBaseInfoByPrjId")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "根据项目编号查询项目费用类型及价格详情，后台")
    public Response getBaseInfoByPrjId(
            @ApiParam(value = "param", required = true)FeePrjDTO dto) {
        CommonResultMap map = new CommonResultMap();
        try {
            map.setData(projectService.getBaseInfoByPrjId(dto));
        } catch (Exception e) {
            logger.error("getBaseInfoByPrjId error.", e);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    private void removeNoRoomProject(List<Map<String,String>> projects)
    {
        if (CollectionUtils.isEmpty(projects))
        {
            return;
        }
        
        // 查询没有发布房间的项目ID集合
        List<String> projectIdList = projectReadMapper.queryNoRoomProject();
        
        if (CollectionUtils.isEmpty(projectIdList))
        {
            return;
        }
        
        Iterator<Map<String, String>> iterater = projects.iterator();
        while (iterater.hasNext())
        {
            Map<String, String> map = iterater.next();
            String prjId = String.valueOf(map.get("prjId"));
            if (projectIdList.contains(prjId))
            {
                iterater.remove();
            }
        }
    }
}
